/**
 * Created by lock
 * Date: 2019-09-22
 * Time: 22:37
 */
package db

import (
	"github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	"github.com/sirupsen/logrus"
	"gochat/config"
	"sync"
	"fmt"
	"time"
)

var dbMap = map[string]*gorm.DB{}
var syncLock sync.Mutex



func ConnectToDB(cfg *config.CommonMysql) (*gorm.DB, error) {
	dsn := fmt.Sprintf("%s@%s/%s?charset=utf8&parseTime=True&loc=Local&timeout=10s&readTimeout=10s&writeTimeout=10s",
		cfg.UserPassword, cfg.Write.HostPort, cfg.DB)

	c, err := mysql.ParseDSN(dsn)
	if err != nil {
		return nil, err
	}

	if cfg.TimeoutInSec > 0 {
		c.Timeout = time.Duration(cfg.TimeoutInSec) * time.Second
	}
	if cfg.WriteTimeoutInSec > 0 {
		c.WriteTimeout = time.Duration(cfg.WriteTimeoutInSec) * time.Second
	}
	if cfg.ReadTimeoutInSec > 0 {
		c.ReadTimeout = time.Duration(cfg.ReadTimeoutInSec) * time.Second
	}

	db, err := gorm.Open("mysql", c.FormatDSN())
	if err != nil {
		return nil, err
	}

	if cfg.Conn.MaxLifeTime > 0 {
		db.DB().SetConnMaxLifetime(time.Duration(cfg.Conn.MaxLifeTime) * time.Second)
	}

	if cfg.Conn.MaxIdle > 0 {
		db.DB().SetMaxIdleConns(cfg.Conn.MaxIdle)
	}

	if cfg.Conn.MaxOpen > 0 {
		db.DB().SetMaxOpenConns(cfg.Conn.MaxOpen)
	}

	return db, nil
}

func InitDB(dbName string) {
	var e error
	// if prod env , you should change mysql driver for yourself !!!
	syncLock.Lock()
	fmt.Println("db",config.Conf.Common.CommonMysql)
	db,err := ConnectToDB(&config.Conf.Common.CommonMysql)
	if err!=nil{
		panic(err)
	}
	dbMap[dbName] = db
	if config.GetMode() == "dev" {
		dbMap[dbName].LogMode(true)
	}
	syncLock.Unlock()
	if e != nil {
		logrus.Error("connect db fail:%s", e.Error())
	}
}

func GetDb(dbName string) (db *gorm.DB) {
	if db, ok := dbMap[dbName]; ok {
		return db
	} else {
		return nil
	}
}

type DbGoChat struct {
}

func (*DbGoChat) GetDbName() string {
	return "gochat"
}
